//
//  XDPickerDateView.m
//  kabu
//
//  Created by XiangDongMBP on 2017/3/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "XDPickerDateView.h"
#import "UIColor+XDHex.h"
#import "NSDate+XDTimerFormatter.h"

@interface XDPickerDateView ()<UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong) UIView *topBgView;
@property (nonatomic, strong) UIView *btnBgView;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) NSArray<NSDate *> *dateArray;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *completeBtn;

@property (nonatomic, strong) NSDate *selDate;   // 初始化指定的滚轮

@end

static CGFloat const kTopBgViewHeight = 180.0;
static CGFloat const kBtnHeight = 40.0;

@implementation XDPickerDateView

- (instancetype)initWithSelDate:(NSDate *)date {
    self = [super init];
    if (self) {
        _selDate = date;
        [self initSubViews];
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    self.frame = [UIScreen mainScreen].bounds;
//    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    self.alpha = 0;
    
//    CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
    CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    UIView *topBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, kTopBgViewHeight)];
//    topBgView.backgroundColor = [UIColor whiteColor];
    topBgView.backgroundColor = [UIColor xd_colorWithHex:0xF3F3F3];
    topBgView.clipsToBounds = YES;
    self.topBgView = topBgView;
    [self addSubview:topBgView];
    
    [self.topBgView addSubview:self.pickerView];
    [self.topBgView addSubview:self.btnBgView];
    
    [self.btnBgView addSubview:self.cancelBtn];
    [self.btnBgView addSubview:self.completeBtn];
}

- (void)showInView:(UIView *)view {
    if (self.superview) {
        return;
    }
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    CGRect viewFrame = [view convertRect:view.bounds toView:nil];
    __block CGRect frame = self.topBgView.frame;
    frame.origin.y = CGRectGetMaxY(viewFrame);
    frame.size.height = 0;
    self.topBgView.frame = frame;
    
    NSInteger selRow = [self selDateOfRow];
    [self.pickerView selectRow:(selRow + 1) inComponent:0 animated:NO];
    
    [UIView animateWithDuration:0.2 animations:^{
        CGRect frame = self.topBgView.frame;
        frame.size.height = kTopBgViewHeight;
        self.topBgView.frame = frame;
        self.alpha = 1;
    } completion:^(BOOL finished) {
        ;
    }];
}

- (void)hideWithAnimation:(BOOL)animate {
    CGFloat duration = animate ? 0.2 : 0.0;
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:duration animations:^{
        CGRect frame = self.topBgView.frame;
        frame.size.height = 0;
        self.topBgView.frame = frame;
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}

- (void)dismiss {
    [self hideWithAnimation:YES];
}

//- (void)buttonTapped:(UIButton *)button {
//    if ([self.delegate respondsToSelector:@selector(eTChSeaSelView:clickedButtonAtIndex:)]) {
//        [self.delegate eTChSeaSelView:self clickedButtonAtIndex:button.tag];
//    }
//    [self hideWithAnimation:YES];
//}

//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//
//    //    for (UIButton * button in self.buttonArray) {
//    //        if ([button pointInside:point withEvent:event]) {
//    //            return button;
//    //        }
//    //    }
//
//    UIView * hitView = [super hitTest:point withEvent:event];
//    if ([hitView isKindOfClass:[UIButton class]]) {
//        return hitView;
//    }
//
//    [self hideWithAnimation:YES];
//    return nil;
//}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self hideWithAnimation:YES];
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.dateArray.count + 1;
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (row == 0) {
        return @"全部时间";
    }
    
    NSDate *date = self.dateArray[row - 1];
    return [date xd_yyyyMM];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    ;
}

#pragma mark - event response
- (void)cancelBtnTapped:(UIButton *)btn {
    [self hideWithAnimation:YES];
}
- (void)completeBtnTapped:(UIButton *)btn {
    NSDate *date = nil;
    NSString *dateStr = @"时间";
    
    NSInteger row = [self.pickerView selectedRowInComponent:0];
    if (row != 0) {
        date = self.dateArray[row - 1];
        dateStr = [date xd_yyyy_MM];
    }
    
    if (self.pickerDateHandle) {
        self.pickerDateHandle(date);
        self.pickerDateHandle = nil;
    }
    
    [self hideWithAnimation:YES];
}

#pragma mark - private methods
- (NSInteger)selDateOfRow {
    __block NSInteger row = - 1;
    [self.dateArray enumerateObjectsUsingBlock:^(NSDate * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([[obj xd_yyyy_MM] isEqualToString:[self.selDate xd_yyyy_MM]]) {
            row = idx;
            *stop = YES;
        }
    }];
    return row;
}

#pragma mark - setters and getters
- (NSArray<NSDate *> *)dateArray {
    if (!_dateArray) {
        NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:15];
        
        // 当前日期
        NSDate *curDate = [NSDate date];
        
        //定义一个遵循某个历法的日历对象
        NSCalendar * curCalendar = [NSCalendar currentCalendar];
        
        // 依次获取15个月的时间
        NSDateComponents *components = [[NSDateComponents alloc] init];
        for (NSInteger i = 0; i < 15; ++i) {
            components.month = i;
            //1个月后的时间
            //这里要注意最后一个参数options，之前设置的为NSCalendarWrapComponents，数学计算。导致3月30号加上三天之后直接变成了3月2号。
            //就是月份没有自动增1
            NSDate * nextdate = [curCalendar dateByAddingComponents:components toDate:curDate options:NSCalendarMatchStrictly];
            
            [mArray addObject:nextdate];
        }
        
        _dateArray = mArray;
    }
    return _dateArray;
}

- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        _cancelBtn.frame = CGRectMake(0, 0, 50, kBtnHeight);
        //        _cancelBtn.backgroundColor = [UIColor yellowColor];
        [_cancelBtn addTarget:self action:@selector(cancelBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}
- (UIButton *)completeBtn {
    if (!_completeBtn) {
        _completeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_completeBtn setTitle:@"确定" forState:UIControlStateNormal];
        CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
        _completeBtn.frame = CGRectMake(width - 50, 0, 50, kBtnHeight);
        //        _completeBtn.backgroundColor = [UIColor yellowColor];
        [_completeBtn addTarget:self action:@selector(completeBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _completeBtn;
}
- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), kTopBgViewHeight - kBtnHeight - 1)];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = [UIColor xd_colorWithHex:0xF3F3F3];
//        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.showsSelectionIndicator = YES;
    }
    return _pickerView;
}

- (UIView *)btnBgView {
    if (!_btnBgView) {
        CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
        _btnBgView = [[UIView alloc] initWithFrame:CGRectMake(0, kTopBgViewHeight - kBtnHeight, width, kBtnHeight - 1)];
        _btnBgView.backgroundColor = [UIColor whiteColor];
        _btnBgView.clipsToBounds = YES;
    }
    return _btnBgView;
}

@end
